//
//  DomainHealthChecker.swift
//  Mediaplayer
//
//  Created by bin hu on 2025/7/16.
//

import Alamofire

class DomainHealthChecker {
    private static var failureRecords = [String: Int]()
    
    static func check(domain: String, completion: @escaping (Result<HealthReport, Error>) -> Void) {
//        // DNS解析检测
//        let ips = DomainHealthChecker.resolveDNS(domain: domain)
        
        let resolved = false
        
        // HTTP健康检测
        AF.request("https:\(domain)/health", requestModifier: { $0.timeoutInterval = 5 })
            .validate()
            .responseData { response in
                switch response.result {
                case .success(let data):
                    let report = HealthReport(
                        domain: domain,
                        dnsResolved: resolved,
                        httpStatus: response.response?.statusCode,
                        latency: response.metrics?.taskInterval.duration,
                        lastError: nil,
                        failureCount: failureRecords[domain] ?? 0
                    )
                    failureRecords[domain] = 0 // 重置失败计数
                    completion(.success(report))
                    
                case .failure(let error):
                    failureRecords[domain] = (failureRecords[domain] ?? 0) + 1
                    let report = HealthReport(
                        domain: domain,
                        dnsResolved: resolved,
                        httpStatus: response.response?.statusCode,
                        latency: response.metrics?.taskInterval.duration,
                        lastError: error.localizedDescription,
                        failureCount: failureRecords[domain] ?? 1
                    )
                    completion(.failure(error))
                }
            }
    }
    
//   static func resolveDNS(domain: String) -> [String] {
//        var ips:[String] = []
//        let host = CFHostCreateWithName(nil, domain as CFString).takeRetainedValue()
//        var success: DarwinBoolean = false
//        
//        CFHostStartInfoResolution(host, .addresses, nil)
//        guard let addresses = CFHostGetAddressing(host, &success)?.takeUnretainedValue() as? [Data] else {
//            return []
//        }
//        
//        for address in addresses {
//            var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
//            address.withUnsafeBytes { ptr in
//                guard let sockaddr = ptr.baseAddress?.assumingMemoryBound(to: sockaddr.self) else { return }
//                getnameinfo(sockaddr, socklen_t(address.count),
//                           &hostname, socklen_t(hostname.count),
//                           nil, 0, NI_NUMERICHOST)
//            }
//            ips.append(String(cString: hostname))
//        }
//        return ips
//    }
//    
//    static func check(domain: String,
//                      timeout: TimeInterval = 5,
//                      completion: @escaping (Result<DNSReport, Error>) -> Void) {
//        let host = CFHostCreateWithName(nil, domain as CFString).takeRetainedValue()
//        var success: DarwinBoolean = false
//        
//        // 设置异步解析超时
//        let timer = DispatchSource.makeTimerSource()
//        timer.schedule(deadline: .now() + timeout)
//        timer.setEventHandler {
//            CFHostCancelInfoResolution(host, .addresses)
//            completion(.failure(NSError(domain: "DNS解析超时", code: -1)))
//        }
//        timer.resume()
//        
//        CFHostStartInfoResolution(host, .addresses, nil)
//        guard let addresses = CFHostGetAddressing(host, &success)?.takeUnretainedValue() as? [Data] else {
//            timer.cancel()
//            completion(.failure(NSError(domain: "DNS解析失败", code: Int(success.rawValue))))
//            return
//        }
//        
//        timer.cancel()
//        var ipList = [String]()
//        for address in addresses {
//            var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
//            address.withUnsafeBytes { ptr in
//                guard let sockaddr = ptr.baseAddress?.assumingMemoryBound(to: sockaddr.self) else { return }
//                getnameinfo(sockaddr, socklen_t(address.count),
//                            &hostname, socklen_t(hostname.count),
//                            nil, 0, NI_NUMERICHOST)
//            }
//            ipList.append(String(cString: hostname))
//        }
//        
//        let report = DNSReport(
//            domain: domain,
//            resolvedIPs: ipList,
//            resolutionTime: Date().timeIntervalSince1970,
//            isSuccessful: !ipList.isEmpty
//        )
//        completion(.success(report))
//    }
//    
//    struct DNSReport {
//        let domain: String
//        let resolvedIPs: [String]
//        let resolutionTime: TimeInterval
//        let isSuccessful: Bool
//    }

}

struct HealthReport {
    let domain: String
    let dnsResolved: Bool
    let httpStatus: Int?
    let latency: TimeInterval?
    let lastError: String?  // 新增错误信息记录
    let failureCount: Int   // 新增连续失败计数
}

//DomainHealthChecker.check(domain: "api.example.com") { result in
//    switch result {
//    case .success(let report):
//        print("健康报告: \(report)")
//        if report.failureCount > 0 {
//            print("该域名历史故障次数: \(report.failureCount)")
//        }
//    case .failure(let error):
//        print("检测失败: \(error.localizedDescription)")
//    }
//}


